<template>
  <div class="borrow-analysis">
      <h2>借阅情况分析</h2>
      <el-row gutter="20">
        <!-- 借阅趋势图表 -->
        <el-col :span="12">
          <div id="borrowTrendChart" style="width: 100%; height: 300px;"></div>
        </el-col>
        <!-- 图书类型分布图表 -->
        <el-col :span="12">
          <div id="bookTypeChart" style="width: 100%; height: 300px;"></div>
        </el-col>
      </el-row>
      <!-- 逾期情况统计 -->
      <el-row gutter="20">
        <el-col :span="24">
          <div id="overdueChart" style="width: 100%; height: 300px;"></div>
        </el-col>
      </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import http from '../utils/axios';
import * as echarts from 'echarts';

// 数据与状态
const borrowedBooks = ref({ content: [], totalElements: 0 });
const pagination = ref({ page: 1, size: 10000 });
const loading = ref(false);
const borrowTrendChart = ref(null);
const bookTypeChart = ref(null);
const overdueChart = ref(null);
const borrowTrendData = ref([]);
const bookTypeData = ref([]);
const overdueData = ref([]);

// 获取借阅记录
const fetchBorrowedBooks = async () => {
  loading.value = true;
  try {
    const response = await http.post("/borrow/all", {
      page: pagination.value.page - 1,
      size: pagination.value.size,
    });
    const records = response.data.content || [];
    const bookNumbers = records.map(record => record.bookNumber);
    const bookDetails = await Promise.all(
      bookNumbers.map(bookNumber => http.get(`/book/${bookNumber}`))
    );
    const bookMap = new Map(bookDetails.map(detail => [detail.data.bookNumber, detail.data]));
    records.forEach(record => {
      record.bookType = bookMap.get(record.bookNumber)?.bookType || '未知';
    });
    borrowedBooks.value = response.data || { content: [], totalElements: 0 };
    updateBorrowTrendStatistics(records);
    updateBookTypeStatistics(records);
    updateOverdueStatistics(records);
  } catch (error) {
    ElMessage.error("获取借阅记录失败：" + error.message);
  } finally {
    loading.value = false;
  }
};

// 统计借阅趋势
const updateBorrowTrendStatistics = (records) => {
  const dateCount = {};
  records.forEach(record => {
    const date = new Date(record.borrowDate);
    const year = date.getFullYear();
    const month = date.getMonth() + 1; // 月份从0开始
    const key = `${year}-${month}`;
    if (dateCount[key]) {
      dateCount[key]++;
    } else {
      dateCount[key] = 1;
    }
  });
  const sortedKeys = Object.keys(dateCount).sort();
  borrowTrendData.value = sortedKeys.map(key => ({
    name: key,
    value: dateCount[key]
  }));
  nextTick(() => {
    if (borrowTrendChart.value) {
      borrowTrendChart.value.setOption({
        xAxis: {
          data: borrowTrendData.value.map(item => item.name)
        },
        series: [{
            data: borrowTrendData.value.map(item => item.value),
            type: 'line'
          }]
      });
    }
  });
};

// 统计图书类型
const updateBookTypeStatistics = (records) => {
  const typeCount = {};
  records.forEach(record => {
    const type = record.bookType;
    if (typeCount[type]) {
      typeCount[type]++;
    } else {
      typeCount[type] = 1;
    }
  });
  bookTypeData.value = Object.keys(typeCount).map(type => ({
    name: type,
    value: typeCount[type]
  }));
  nextTick(() => {
    if (bookTypeChart.value) {
      bookTypeChart.value.setOption({
        series: [
          {
            data: bookTypeData.value
          }
        ]
      });
    }
  });
};

// 统计逾期情况
const updateOverdueStatistics = (records) => {
  const overdueCount = records.filter(record => record.processing === 1).length;
  overdueData.value = [
    { name: '逾期待处理', value: overdueCount },
    { name: '已处理', value: records.length - overdueCount }
  ];
  nextTick(() => {
    if (overdueChart.value) {
      overdueChart.value.setOption({
        series: [
          {
            data: overdueData.value
          }
        ]
      });
    }
  });
};

// 初始化图表
const initBorrowTrendChart = () => {
  borrowTrendChart.value = echarts.init(document.getElementById('borrowTrendChart'));
  borrowTrendChart.value.setOption({
    title: {
      text: '借阅趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: borrowTrendData.value.map(item => item.name)
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: borrowTrendData.value.map(item => item.value),
        type: 'line'
      }
    ]
  });
};

const initBookTypeChart = () => {
  bookTypeChart.value = echarts.init(document.getElementById('bookTypeChart'));
  bookTypeChart.value.setOption({
    title: {
      text: '借阅图书类型分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '图书类型',
        type: 'pie',
        radius: '50%',
        data: bookTypeData.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  });
};

const initOverdueChart = () => {
  overdueChart.value = echarts.init(document.getElementById('overdueChart'));
  overdueChart.value.setOption({
    title: {
      text: '逾期待处理统计',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '逾期情况',
        type: 'pie',
        radius: '50%',
        data: overdueData.value,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  });
};

// 页面加载时获取借阅记录
onMounted(() => {
  fetchBorrowedBooks().then(() => {
    nextTick(() => {
      initBorrowTrendChart();
      initBookTypeChart();
      initOverdueChart();
    });
  });
});
</script>

<style scoped>
.borrow-analysis {
  padding: 20px;
}

</style>
